<template>
    <div class="colorBox">
        主题颜色： <el-color-picker v-model="colors.primary" size="small" @change="submitForm"
        :predefine="['#409EFF', '#1890ff', '#304156','#212121','#11a983', '#13c2c2', '#6959CD', '#f5222d', ]"
        ></el-color-picker>
         <!-- <el-dialog
         :close-on-click-modal='false'
        center
        title="主题色"
        :visible.sync="themeDialogVisible"
        append-to-body
        width="400px">
        <el-form
            :model="colors"
            :rules="rules"
            ref="form"
            class="theme-form"
            label-position="top"
            label-width="70px">
            <el-form-item>
                <el-color-picker v-model="colors.primary"></el-color-picker>
            </el-form-item>
            <el-form-item>
            <el-button type="primary" @click="submitForm">切换</el-button>
            </el-form-item>
        </el-form>
        </el-dialog> -->
    </div>
</template>

<script>
  import generateColors from './util/color'
  import objectAssign from 'object-assign'
  import otherColor from '@/utils/config/otherColor'
    export default {
        props: {
            value: {
                type: String,
                default: ''
            }
        },
        data() {
            return {
                themeDialogVisible: false,
                colors: {
                    primary: '#2285dc'
                },
                rules: {
                },
                originalStyle: '',
                styleDom: document.createElement('style'),
                styleDom2: document.createElement('style')
            }
        },
        mounted(){
            
        },
        methods:{
            showThemeDialog () {
                this.themeDialogVisible = true
            },
            submitForm () {
                const _this = this;
                    this.themeDialogVisible = false
                    this.$store.commit('setColor', this.colors.primary);
                    this.setOtherThemeColor(this.colors.primary);
                    this.$emit('input', this.colors.primary);
                    this.$emit('changeConfig'); // 通知整体config进行修改，进行存入缓存。
                    this.colors = objectAssign({}, this.colors, generateColors(this.colors.primary))
                    this.writeNewStyle()
            },
            writeNewStyle () {
                let cssText = this.originalStyle
                Object.keys(this.colors).forEach(key => {
                cssText = cssText.replace(new RegExp('(:|\\s+)' + key, 'g'), '$1' + this.colors[key])
                })
                // if (this.originalStylesheetCount === document.styleSheets.length) {
                // // const style = document.createElement('style')
                // this.styleDom2.innerText = cssText
                // document.head.appendChild(this.styleDom2)
                // } else {
                // document.head.lastChild.innerText = cssText
                // }
                this.styleDom2.innerText = cssText;
                this.styleDom.type = "text/css"

            },
            getStyleTemplate (data) {
                const colorMap = {
                '#3a8ee6': 'shade-1',
                '#409eff': 'primary',
                '#53a8ff': 'light-1',
                '#66b1ff': 'light-2',
                '#79bbff': 'light-3',
                '#8cc5ff': 'light-4',
                '#a0cfff': 'light-5',
                '#b3d8ff': 'light-6',
                '#c6e2ff': 'light-7',
                '#d9ecff': 'light-8',
                '#ecf5ff': 'light-9'
                }
                Object.keys(colorMap).forEach(key => {
                const value = colorMap[key]
                data = data.replace(new RegExp(key, 'ig'), value)
                })
                return data
            },
            getFile (url, isBlob = false) {
                return new Promise((resolve, reject) => {
                const client = new XMLHttpRequest()
                client.responseType = isBlob ? 'blob' : ''
                client.onreadystatechange = () => {
                    if (client.readyState !== 4) {
                    return
                    }
                    if (client.status === 200) {
                    const urlArr = client.responseURL.split('/')
                    resolve({
                        data: client.response,
                        url: urlArr[urlArr.length - 1]
                    })
                    } else {
                    reject(new Error(client.statusText))
                    }
                }
                client.open('GET', url)
                client.send()
                })
            },
            getIndexStyle () {
               return this.getFile('//unpkg.com/element-ui/lib/theme-chalk/index.css')
                .then(({ data }) => {
                    this.originalStyle = this.getStyleTemplate(data);
                    return Promise.resolve();
                })
            },
            getSeparatedStyles () {
                this.getFile('//unpkg.com/element-ui/lib/theme-chalk/')
                .then(({ data }) => {
                    return data.match(/href="[\w-]+\.css"/g).map(str => str.split('"')[1])
                })
                .then(styleFiles => {
                    return Promise.all(styleFiles.map(file => {
                    return this.getFile(`//unpkg.com/element-ui/lib/theme-chalk/${file}`)
                    }))
                })
                .then(files => {
                    this.styleFiles = files.map(file => {
                    return {
                        name: file.url,
                        data: this.getStyleTemplate(file.data)
                    }
                    })
                })
            },
            // 动态添加需要修改的color 
            setOtherThemeColor (color) {
                 this.styleDom.innerText = "";
                 let copyColor = {};
                 Object.assign(copyColor, otherColor)
                 for (const key in copyColor) {
                     if (copyColor.hasOwnProperty(key)) {
                         const cssString = copyColor[key];
                         const newCssStr = cssString.replace(/themeColor/, color);
                         this.styleDom.innerText += (key + newCssStr);
                     }
                 }
                 this.styleDom.type = "text/css"
            }
        },
        created() {
            this.colors.primary = this.value;
            this.$store.commit('setColor', this.value);
            const loading = this.$loading({
                lock: true,
                text: '加载主题中....',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            this.getIndexStyle().then(() => {
                this.colors = objectAssign({}, this.colors, generateColors(this.colors.primary));
                this.writeNewStyle();
                this.setOtherThemeColor(this.value);
                loading.close();
            })
            this.getSeparatedStyles()
            
        },
        mounted () {
            this.$nextTick(() => {
                this.originalStylesheetCount = document.styleSheets.length;
            })
             document.getElementsByTagName('head')[0].appendChild(this.styleDom);
             document.getElementsByTagName('head')[0].appendChild(this.styleDom2);
        },
        watch: {
            value() {
                this.colors.primary = this.value;
                this.$store.commit('setColor', this.value);
            }
        },
        computed: {
        }
    }
</script>

<style scoped>
.colorBox{
    display: flex;
    margin-left: 5px;
    margin-right: 5px;
    align-items: center;
    justify-content: space-between;
}
.changeColor{
    cursor: pointer;
}
.theme-form {
  text-align: center;
}
</style>
